# -*- encoding:utf-8 -*-
# __author__ = 'chenyongbing'
# __poject__ = 'ops_platform'
# __datetime__ = '2022/7/11'
# __name__ = 'tasks.py'
from .models import WorkOrder
from .models import DemandOrder, LobEnvSetting
from apps.cicd import flows
from celery import shared_task
from django.db import transaction
import re
# Create your code here.


@shared_task
def workorder_auto_do(did, username='auto'):
    dorder = DemandOrder.objects.get(id=did)
    if not re.search('auto', dorder.step.function):
        return True

    flow_function_name = flows.get_flow_function(dorder.order_type)
    next_step = dorder.step.yes_step

    total_count = 0
    finish_count = 0
    cancel_count = 0
    success_count = 0
    for worder in dorder.orders.filter(delete=0):
        total_count += 1
        if worder.status == 'finish':
            finish_count += 1
            continue
        elif worder.status == 'cancel':
            cancel_count += 1
            continue
        elif worder.status != 'wait':
            continue
        cur_workder_step = worder.steps.last()
        if cur_workder_step.step != dorder.step:
            success_count += 1
            continue
        if cur_workder_step.status in ['wait', 'fail']:
            flow_function = getattr(flows, flow_function_name)(workorder=worder,
                                                                           username=username)
            ret = getattr(flow_function, 'do')(dorder.step.function, action='yes')
            status = ret.get('status')
            next_step_function = ret.get('next_step_function')
            if next_step_function == 'end__finish':
                finish_count += 1
            elif next_step_function == 'end__cancel':
                cancel_count += 1
            elif status == 'finish':
                success_count += 1


    if success_count + finish_count + cancel_count == total_count:
        dorder.step_id = next_step.id
        dorder.status = 'finish' if finish_count==total_count else 'cancel' if cancel_count==total_count else 'wait'
        dorder.save()

    return True




@shared_task
def workorder_auto_do_task(oid, function, username='auto'):
    workorder = WorkOrder.objects.get(id=oid)
    flow_function_name = flows.get_flow_function(workorder.order_type)
    flow_function = getattr(flows, flow_function_name)(workorder=workorder,
                                                       username=username)
    ret = getattr(flow_function, 'do')(function, action='yes')
    return ret


    